package com.axxc.jpa.config;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.axxc.jpa.entity.VisitLogEntity;
import com.axxc.jpa.service.IVisitLogService;

/**
 * 
 * @ClassName: WebLogAspect
 * @Description: web层切面
 * @author 熊小川
 * @date 2018年5月18日 下午9:47:55
 * @See http://www.spring4all.com/article/258#comment
 */
@Aspect
@Component
@Order(5)
public class WebLogAspect {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private IVisitLogService visitLogService;

	private String responseJson = "";
	private String visitUrl = "";
	private String visitHttpMethod = "";
	private String visitIp = "";
	private Date visitDate;
	private String visitMethod = "";
	private String visitAge = "";

	@Pointcut("execution(public * com.axxc.*.web..*.*(..))")
	public void webLog() {
	}

	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) throws Throwable {
		// 接收到请求，记录请求内容
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		// 记录请求内容
		this.visitUrl = request.getRequestURL().toString();
		this.visitHttpMethod = request.getMethod();
		this.visitIp = request.getRemoteAddr();
		this.visitDate = new Date();
		this.visitMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
		this.visitAge = JSONObject.toJSONString(joinPoint.getArgs());

		logger.info("URL : " + visitUrl);
		logger.info("HTTP_METHOD : " + visitHttpMethod);
		logger.info("VISIT IP : " + visitIp);
		logger.info("VISIT DATE : " + visitDate);
		logger.info("CLASS_METHOD : " + visitMethod);
		logger.info("ARGS : " + visitAge);

	}

	@AfterReturning(returning = "result", pointcut = "webLog()")
	public void doAfterReturning(Object result) throws Throwable {
		// 处理完请求，返回内容
		this.responseJson = JSONObject.toJSONString(result);
		VisitLogEntity visitLogEntity = new VisitLogEntity();
		visitLogEntity.setResponseJson(responseJson.length() >= 255 ? "responseJson length to long >255" : responseJson);
		visitLogEntity.setVisitArg(visitAge.length() >= 255 ? "visitAge length to long >255" : visitAge);
		//visitLogEntity.setResponseJson(responseJson);
		// visitLogEntity.setVisitArg(visitAge);
		visitLogEntity.setVisitDate(visitDate);
		visitLogEntity.setVisitHttpMethod(visitHttpMethod);
		visitLogEntity.setVisitIp(visitIp);
		visitLogEntity.setVisitMethod(visitMethod);
		visitLogEntity.setVisitUrl(visitUrl);
		try {
			VisitLogEntity logEntity = visitLogService.save(visitLogEntity);
			logger.info("visitEntity:id->{}", logEntity.getId());
			logger.info("RESPONSE : " + responseJson);
		} catch (DataIntegrityViolationException e) {
			logger.error("保存日志失败,请求URL:{}", visitLogEntity.getVisitUrl());
		}

	}

}